<template>
  <q-page class="cc-admin row">

    <div class="col bg-white shadow-2 q-pa-md q-ma-sm">
      <q-table
        flat
        color="primary"
        table-class="bg-blue-2 text-gray-3"
        table-style="border: 1px solid #1576e8;"

        separator="cell"
        :columns="columns"
        :data="list"
        row-key="id"
        :pagination.sync="pagination"
        :visible-columns="group"
        @request="query"
        :rows-per-page-options="[10,20,50,100]"
        :loading="loading"
        selection="multiple"
        :selected.sync="selected"
      >
        <template v-slot:top="table">
          <div class="row no-wrap full-width">
            <q-input
              clearable
              outlined
              dense
              placeholder="请输入关键字搜索"
              class="on-left"
              @input="query"
              debounce="500"
              v-model="key"
            >
              <template #append>
                <q-btn flat round icon="search" color="primary" @click="query" :loading="loading">
                  <q-tooltip>搜索</q-tooltip>
                </q-btn>
              </template>
            </q-input>
            <q-space />
            <div class="q-gutter-xs">
              <q-btn icon="add" no-wrap color="primary" label="新建" @click="add" />
              <q-btn
                no-wrap
                v-show="$q.screen.gt.sm"
                label="导入"
                icon="mdi-cloud-upload-outline"
                :loading="importing"
                color="primary"
                @click="importExcel"
              >
                <q-uploader
                  auto-upload
                  ref="excelUploader"
                  :max-files="1"
                  class="hidden"
                  :url="importExcelUrlFull"
                  field-name="file"
                  :headers="headers"
                  @uploaded="importedExcel"
                />
              </q-btn>
              <q-btn
                no-wrap
                v-show="$q.screen.gt.sm"
                :loading="exporting"
                label="导出"
                icon="mdi-cloud-download-outline"
                color="primary"
                @click="exportExcel('服务器列表')"
              />
              <q-btn
                :disable="selected.length === 0"
                no-wrap
                v-show="$q.screen.gt.md"
                color="negative"
                label="批量删除"
                @click="showConfirm()"
                icon="mdi-delete-variant"
              />
              <q-btn
                color="primary"
                label="切换全屏"
                no-wrap
                v-show="$q.screen.gt.md"
                @click="table.toggleFullscreen"
                :icon="table.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
              />
              <q-btn-dropdown
                color="primary"
                label="自选列"
                icon="view_list"
                no-wrap
                v-show="$q.screen.gt.md"
              >
                <q-list>
                  <q-item tag="label" v-for="item in columns" :key="item.name">
                    <q-item-section avatar>
                      <q-checkbox v-model="group" :val="item.name" />
                    </q-item-section>
                    <q-item-section>
                      <q-item-label>{{item.label}}</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-btn-dropdown>
            </div>
          </div>
        </template>
        <template #body-cell-loginType="props">
          <q-td key="loginType" :props="props">
            {{getDictLabel(loginType,props.row.loginType) }}
          </q-td>
        </template>
        <template #body-cell-opt="props">
          <q-td :props="props" :auto-width="true">
            <q-btn flat round dense color="primary" icon="edit" @click="edit3(props.row)">
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <btn-del label="合同管理" @confirm="del(props.row)" />
          </q-td>
        </template>
      </q-table>
    </div>
    <q-dialog v-model="dialogVisible" >
      <q-card style="min-width: 1000px;">
        <q-toolbar>
          <q-toolbar-title>图像预览</q-toolbar-title>
          <q-btn icon="close" flat round dense v-close-popup />
        </q-toolbar>
        <q-card-actions>
          <img width="100%" :src="dialogImageUrl" alt="">
        </q-card-actions>
      </q-card>
    </q-dialog>

    <q-dialog maximized flat persistent ref="dialog">
      <q-form @submit="onSubmit" class="dialog_card column" @reset="onReset">
        <h5 class="view_title justify-between q-px-md">
          {{editType}}合同管理
          <q-btn dense outline round icon="clear" size="sm" v-close-popup />
        </h5>
        <q-scroll-area class="col">
          <div class="row q-col-gutter-x-md dialog_form q-pa-md">
            <q-input v-model="form.isEdit" type="hidden"   />
            <div class="col-6"  v-if="editType =='编辑'">
              <h5><q-icon name="star" color="red"/> ID：</h5>
              <div class="row no-wrap">
                <div class="bg-green-2" style="padding: 10px">
                  <q-input v-model="form.id"   />
                </div>
              </div>
            </div>
            <div class="col-12">
              <h5>
                <q-icon name="star" color="red" />收款计划：
              </h5>
              <template>
                <div class="q-pa-md">
                  <q-table :data="plan_data" :columns="columns_plan" row-key="name"
                  >
                    <template v-slot:body="props">
                      <q-tr :props="props">
                        <q-td key="plan_time" :props="props" class="col-3">
                          <q-input style="width:50%"  outlined dense v-model="props.row.plan_time" type="text"  />
                        </q-td>
                        <q-td key="plan_date" :props="props">

                          <q-input style="width:50%"  outlined dense v-model="props.row.plan_date" type="text"  />
                          <!--<q-popup-edit v-model="props.row.plan_date" title="编辑计划日期" labelCancel="取消" buttons v-slot="scope">
                            <q-input type="text" v-model="scope.value" dense autofocus />
                            <q-btn-group rounded>
                              <q-btn rounded color="primary" label="确定"  />
                            </q-btn-group>
                          </q-popup-edit>-->
                        </q-td>
                        <q-td key="plan_money" :props="props">
                          <div class="text-pre-wrap">
                            <q-input style="width:50%"  outlined dense v-model="props.row.plan_money" type="text"  />
                          </div>

                        </q-td>
                        <q-td key="percent" :props="props">
                          <q-input style="width:50%"  outlined dense v-model="props.row.percent" type="text"  />

                        </q-td>
                        <q-td key="opt" :props="props">
                          <q-btn label="添加" color="primary" @click="addTable(props.row.index)" />
                          <q-btn label="删除" color="deep-orange" @click="delTable(props.row.index)" />
                        </q-td>
                      </q-tr>
                    </template>
                  </q-table>
                </div>
              </template>
            </div>
            <div class="col-6 clear">
              <h5><q-icon name="star" color="red"/> 电话：</h5>
              <div class="row no-wrap">
                <div class="bg-green-2" style="padding: 10px">
                  <q-input bottom-slots v-model="form.phone" label="请输入电话" counter >
                    <template v-slot:prepend>
                      <q-icon name="place" />
                    </template>
                    <template v-slot:append>
                      <q-icon name="close" @click="form.phone = ''" class="cursor-pointer" />
                    </template>
                    <template v-slot:hint> 输入 </template>
                  </q-input>
                </div>
                <q-btn label="测试" color="primary" @click="testLogin" />
              </div>
            </div>
            <div class="col-3">
              <h5>
                <q-icon name="star" color="red" />安装工人：
              </h5>
              <div class="bg-green-2" style="padding: 10px">
                <q-select color="white-2" bg-color="green" filled v-model="form.worker" :options="workerOptions">
                  <template v-slot:prepend>
                    <q-icon name="mdi-triangle" class="text-dark" />
                  </template>
                </q-select>
              </div>
            </div>
            <div class="col-3">
              <h5>业务所属公司：</h5>
              <div class="bg-green-2" style="padding: 10px">
                <q-select color="white-2" bg-color="green" filled v-model="form.company_id" :options="companyOptions">
                  <template v-slot:prepend>
                    <q-icon name="event" />
                  </template>
                </q-select>

              </div>
            </div>
            <div class="col-6">
              <h5>经销商：</h5>
              <q-input outlined name="seller_id" v-model="form.seller_id"  />
            </div>
            <div class="col-6">
              <h5>备注：</h5>
              <div class="bg-green-2" style="padding: 10px">
                <q-input bottom-slots name="remark" v-model="form.remark" label="请输入备注内容" counter >
                  <template v-slot:prepend>
                    <q-icon name="place" />
                  </template>
                  <template v-slot:append>
                    <q-icon name="close" @click="form.remark = ''" class="cursor-pointer" />
                  </template>
                  <template v-slot:hint> 输入 </template>
                </q-input>
              </div>
            </div>
            <div class="col-12" >
              <h5>附件文件：</h5>
              <div class="row no-wrap">
                <q-input class="col" readonly outlined dense v-model="form.keyFile" />
                <q-btn outline no-wrap label="上传" color="primary" @click="selectFiles">
                  <q-uploader
                    auto-upload
                    ref="keyFileUploader"
                    :max-files="1"
                    class="hidden"
                    :url="uploadUrl"
                    field-name="file"
                    :headers="headers"
                    @uploaded="uploadedFiles"
                  />
                </q-btn>
              </div>
            </div>
            <div class="col-12">
              <div class="q-gutter-md row items-start">
                <q-img
                  v-for="f in file_list"
                  :key="f.id"
                  transition="fade"
                  :src="(f.url)"
                  style="width: 150px"
                  ratio="1"
                  spinner-color="white"
                  class="rounded-borders"
                >
                  <q-btn
                    class="absolute-top"
                    dense round
                    @click="zoomImg(f.url)"
                    icon="mdi-magnify-scan"
                    v-if="f.type=='jpg' || f.type=='png' "
                  >
                  </q-btn>
                  <q-btn
                    class="absolute-bottom"
                    dense round
                    @click="go_file(f.file_path)"
                    icon="mdi-magnify-scan"
                    v-if="f.type=='xls' || f.type=='xlsx' "
                  >
                  </q-btn>
                </q-img>
              </div>
            </div>
            <div class="col-12">
              <h5>审批人：</h5>
              <q-input outlined dense v-model="form.approver_id" />
            </div>
          </div>
        </q-scroll-area>
        <div class="row q-col-gutter-x-md">
          <div class="col-md-3 text-right">
            <q-btn
              class="no-border-radius"
              unelevated
              type="submit"
              :loading="loading"
              icon="camera_enhance"
              color="primary"
              label="保 存"
              size="md"
            >
              <template v-slot:loading>
                <q-spinner-hourglass class="on-left" />保存...
              </template>
            </q-btn>
          </div>
          <div class="col-md-3 text-center">
            <q-btn
              class="no-border-radius"
              unelevated
              type="reset"
              icon="camera_enhance"
              color="grey"
              label="清 除"
              size="md"
            ></q-btn>
          </div>
          <div class="col-md-3 text-left">
            <q-btn
              class="no-border-radius"
              unelevated
              v-close-popup
              type="button"
              outline style="color: goldenrod;"
              icon="camera_enhance"
              label="关闭"
              size="md"
            ></q-btn>
          </div>
        </div>
      </q-form>
    </q-dialog>
    <!-- 编辑 -->

    <confirm ref="confirmDialog" :msg="confirmMsg" @confirm="deleteBatch()" />
  </q-page>
</template>

<script>
import { IndexMixin } from 'boot/mixins';
import { getDictLabel } from 'boot/dictionary';
import confirm from 'components/confirm';
import { requiredTest } from 'boot/inputTest';
let now_date = new Date()
let year = now_date.getFullYear();
let month = now_date.getMonth() + 1 < 10 ? "0" + (now_date.getMonth() + 1) : now_date.getMonth() + 1
let day = now_date.getDate() < 10 ? "0" + now_date.getDate() : now_date.getDate()
let plan_data = [
  {
    plan_time: '计划次数1',
    plan_date:  year + '-' + month + '-'+ day ,
    plan_money: 100.00,
    percent: 20,
    delFlag: 0,
    index: 1 ,
  },

];
export default {
  name: 'MntServer',
  mixins: [IndexMixin],
  components: {
    confirm,
  },

  data() {
    return {
      plan_data,
      companyOptions:[{
        label: '意科公司',
        value: '意科公司'
      },{
        label: '意科公司2',
        value: '意科公司2'
      },{
        label: '意科公司3',
        value: '意科公司3'
      }],
      workerOptions:[{
        label: '张工',
        value: '张工'
      },{
        label: '王工',
        value: '王工'
      },{
        label: '李工',
        value: '李工'
      }],
      columns: [
        {
          name: 'id', align: 'center', label: '序号', field: 'id', required: true,
        },
        {
          name: 'phone', align: 'left', label: '电话', field: 'phone', show: false,
        },
        {
          name: 'worker', align: 'left', label: '安装工人', field: 'worker',
        },
        {
          name: 'company_id', align: 'left', label: '所属公司', field: 'company_id',
        },
        {
          name: 'seller_id', align: 'left', label: '经销商', field: 'seller_id',
        },

        {
          name: 'approver_id', align: 'left', label: '审批人', field: 'approver_id',
        },
        {
          name: 'create_time', align: 'left', label: '创建时间', field: 'create_time',
        },
        {
          name: 'remark', align: 'left', label: '备注', field: 'remark',
        },
        {
          name: 'opt', align: 'center', label: '操作', field: 'id',
        },
      ],
      columns_plan: [
        { name: 'plan_time',
          label: '期数',
          prop: '$index',
          align: 'left',
          sortable: true,
        },
        { name: 'plan_date',
          label: '计划账期',
          prop: 'plan_date',
          align: 'left',
          render: (h, { row, index }) => { }},
        //{ name: 'plan_date', align: 'center', label: '计划日期', field: 'plan_date', sortable: true },
        { name: 'plan_money', label: '计划金额', field: 'plan_money',align: 'left',  },
        { name: 'percent', label: '比例',align: 'left', field: 'percent' },
        {
          name: 'opt',
          label: '操作',
          align: 'center',
        },
      ],
      loginType: [{ value: 'password', label: '密码' }, { value: 'keyFile', label: '证书文件' }],
      showQuery: true,
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.BASE_URL}/file/upload`,
      imgUrl: `${process.env.BASE_URL}/file/static`,
      url: {
        list: '/contract/getlist',
        add: '/contract/add',
        edit: '/contract/edit',
        getPlanListById:'/contract/getPlanListById',
        testLogin: '/contract/testLogin',
        delete: '/contract/delete',
        deleteBatch: '/contract/deleteBatch',
        exportXlsUrl: '/contract/exportXls',
        importExcelUrl: '/contract/importExcel',
      },
      attachments: [],
      mainId: '123456',
      type: 'img',
      file_list: [],
      dialogVisible: false,
      dialogImageUrl: '',
      isEdit:0,
    };
  },
  methods: {
    edit3(p) {
      //console.log('edit3')
      this.isEdit = 1
      this.file_list = [] //初始化附件
      this.plan_data = [
        {
          plan_time: '计划次数1',
          plan_date:  year + '-' + month + '-'+ day ,
          plan_money: 100.00,
          percent: 20,
          delFlag: 0,
          index: 1 ,
        },

      ];//初始化计划
      for(let i=0 ; i < this.workerOptions.length ; i++){
        if( this.workerOptions[i].value == p.worker){
          p.worker = this.workerOptions[i]
        }
      }
      for(let i=0 ; i < this.companyOptions.length ; i++){
        if( this.companyOptions[i].value == p.company_id){
          p.company_id = this.companyOptions[i]
        }
      }
      //console.log(p)
      this.editType = '编辑';
      this.form = {
        ...p,
      };
      this.$refs.dialog.show();
      this.getPlanListById(p.id)
    },
    zoomImg(path) {
      this.dialogImageUrl = `${path}`;
      this.dialogVisible = true;
    },
    getPlanListById( plan_id ){
      this.$axios.get(this.url.getPlanListById+ '?id=' + plan_id ).then((r) => {
        if (r.result.success) {
          if(r.result.records.length > 0){
            this.plan_data = r.result.records
          }
          if( r.result.file_list.length > 0){
            let file_list_tmp = r.result.file_list
            for( let i= 0 ; file_list_tmp.length ; i++){
              this.file_list.push( {id: file_list_tmp[i].id , type: file_list_tmp[i].file_type,  url: file_list_tmp[i].visit_file_url} )
            }
          }
        } else {
          console.log('--plan_data--null')
        }
      }).finally(() => {
        console.log('--')
      });
    },
    selectFiles() {
      this.$refs.fileUploader.pickFiles();
    },
    uploadedFiles({ xhr }) {
      const response = JSON.parse(xhr.responseText);
      if (response.success) {
        //this.form.avatar = response.message;
        this.$q.notify('上传成功')
        if(response.result.file_type == 'xls' ||  response.result.file_type == 'xlsx' ){
          this.file_list.push({id: response.result.file_id , type: 'xlsx', file_path:response.result.visit_file_url,  url: 'http://test4.geekwonderland.net/static/excel_png.png'})
        }else{
          this.file_list.push({id: response.result.file_id , type:response.result.file_type,  url: response.result.visit_file_url})
        }
        this.attachments.push(response.result.file_id)
        console.log(this.file_list)
      } else {
        this.$q.notify({
          color: 'red',
          message: '上传失败',
        });
      }
      this.$refs.fileUploader.removeUploadedFiles();
    },
    addTable(id){
      let count = this.plan_data.length
      this.plan_data.push({
          plan_time: '计划次数'+ (count+1),
          plan_date: year + '-' + month + '-'+ day,
          plan_money: 100.00,
          percent: 20,
          delFlag: 0,
          index: count+1 ,
        }
      )
      //console.log(id + '-'+count)
      console.log( this.plan_data )
    },
    delTable(id){
      let i = 0
      let l = 0
      for(let item in this.plan_data){
        if(item.index == id){
          l = i
          i++
        }
      }
      this.plan_data.splice(l,1)
      if(this.plan_data.length == 0){
        this.plan_data.push({
            plan_time: '计划次数1' ,
            plan_date: year + '-' + month + '-'+ day,
            plan_money: 100.00,
            percent: 20,
            delFlag: 0,
            index: 1 ,
          }
        )
      }
    },
    requiredTest,
    testLogin() {
      this.$q.loading.show();
      this.$axios.put(this.url.testLogin, this.form).then((r) => {
        if (r.success) {
          this.$info(r.message);
        } else {
          this.$error(r.message);
        }
      }).finally(() => {
        this.$q.loading.hide();
      });
    },
    importKeyFile() {
      this.$refs.keyFileUploader.pickFiles();
    },
    importedKeyFile({ xhr }) {
      this.$refs.keyFileUploader.removeUploadedFiles();
      const { response } = xhr;
      const res = JSON.parse(response);
      if (res.success) {
        this.form.keyFile = res.message;
      } else {
        this.$error(res.message);
      }
    },
    addBefore() {
      // this.form.catalogId = this.catalog;
      return true;
    },
    addAfter() {
      this.form.plan_data = this.plan_data;
      this.queryImages();
      return true;
    },
    selectCatalog(n) {
      this.catalog = n;
      this.query();
    },
    getDictLabel,
    initDict() {
    },
    onSubmit (evt) {
      this.form.attachments = this.attachments
      this.form.plan_data = this.plan_data
      this.form.isEdit = this.isEdit
      console.log( this.form  )
      this.$axios.post('/contract/add',this.form).then((r) => {
        this.babyWord = r;
        if(r.success = true){
          this.$q.notify({ position: 'top', color: 'info', textColor: 'white', icon: 'cloud_done', group: false, html: true, message: '保存成功！！',});
          this.onReset()
        }else{
          this.$q.notify({ position: 'top', color: 'error', textColor: 'red', icon: 'cloud_done', group: false, html: true, message: '保存失败！！',});
        }
      });
      //evt.target.submit()
    },
    onReset(){
      this.form = {
        phone : '' ,
        remark : '',
        approver_id : '',
        seller_id : '',
        company_id : '',
      }
    },
    queryImages() {
      this.$axios.get(`/file/listByMainId?mainId=${this.form.id}`).then(({ result }) => {
        this.attachments = result;
      });
    },
    go_file(file_path){
      console.log(file_path)
      window.open(file_path,'文件')
    },
  },
  computed: {
    imgList() {
      return this.attachments.filter((f) => f.type === 'image');
    },
    videoList() {
      return this.attachments.filter((f) => f.type === 'video');
    },
  },
  mounted() {
    this.initDict();
  },
};
</script>

<style lang="stylus"></style>
